package org.schhx.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.schhx.io.Resources;
import org.schhx.session.Configuration;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author shanchao
 * @date 2021/1/30
 */
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        configuration = new Configuration();
    }

    public Configuration parse(InputStream inputStream) throws Exception {
        Document document = new SAXReader().read(inputStream);
        Element root = document.getRootElement();

        dataSourceElement((Element) root.selectSingleNode("dataSource"));
        mapperElement((Element) root.selectSingleNode("mappers"));

        return configuration;
    }

    private void dataSourceElement(Element parent) throws Exception {
        List<Element> property = parent.selectNodes("property");
        Properties properties = new Properties();
        for (Element ele : property) {
            String name = ele.attributeValue("name");
            String value = ele.attributeValue("value");
            properties.put(name, value);
        }

        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(properties.getProperty("driverClass"));
        dataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        dataSource.setUser(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));

        configuration.setDataSource(dataSource);

    }

    private void mapperElement(Element parent) throws DocumentException {
        List<Element> mappers = parent.selectNodes("mapper");
        for (Element mapper : mappers) {
            String resource = mapper.attributeValue("resource");
            XMLMapperBuilder mapperBuilder = new XMLMapperBuilder(configuration);
            mapperBuilder.parse(Resources.getResourceAsStream(resource));
        }
    }


}
